import base64

from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.db.models import Q
from account.models import User
from .models import ArticleColumn, Article
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger


@login_required(login_url='/account/login/')
def article_column(request):
    try:
        columns = ArticleColumn.objects.filter(user=request.user)
        return render(request, "article_column.html", {"columns": columns})
    except Exception as e:
        return render(request, '500.html', {'error': e})


@require_POST
@csrf_exempt
@login_required(login_url='/account/login/')
def add_column(request):
    column_name = request.POST.get('column')
    out = {'status': None, 'msg': None}
    try:
        tag = ArticleColumn(user=request.user, c_name=column_name)
        tag.save()
        out['status'] = 'true'
        out['msg'] = '文章栏目添加成功'
    except Exception as e:
        out['status'] = 'false'
        out['msg'] = '此栏目已存在，请更换名称'
    finally:
        return JsonResponse(out)


@require_POST
@csrf_exempt
@login_required(login_url='/account/login/')
def rename_column(request):
    out = {'status': None, 'msg': None}
    c_id = request.POST.get('column_id')
    c_name = request.POST.get('column_name')
    try:
        obj = ArticleColumn.objects.get(pk=c_id)
        obj.column = c_name
        obj.save()
        out['status'] = 'true'
        out['msg'] = '栏目修改成功'
    except Exception as e:
        out['status'] = 'false'
        out['msg'] = '修改失败'
    finally:
        return JsonResponse(out)


@require_POST
@csrf_exempt
@login_required(login_url='/account/login/')
def del_column(request):
    out = {'status': None, 'msg': None}
    c_id = request.POST.get('column_id')
    try:
        ArticleColumn.objects.get(pk=c_id).delete()
        out['status'] = 'true'
        out['msg'] = '栏目删除成功'
    except Exception as e:
        out['status'] = 'false'
        out['msg'] = '删除失败'
    finally:
        return JsonResponse(out)


def show_column_article(request):
    c_id = request.GET.get('c_id')
    column = request.GET.get('c_name')
    if c_id:
        column = ArticleColumn.objects.get(pk=c_id).c_name
        a_list = Article.objects.filter(c_id=c_id)
    else:
        a_list = Article.objects.filter(c_name=column)
    c = {
        'a_list': a_list,
        'column': column
    }
    return render(request, 'show_column_article.html', c)


@login_required(login_url='/account/login/')
@csrf_exempt
def article_post(request):
    if request.method == "POST":
        title = request.POST.get('title')
        body = request.POST.get('body')
        c_name = ArticleColumn.objects.get(pk=request.POST.get('column_id')).c_name
        c = {}
        try:
            newArticle = Article(u=request.user,
                                 title=title,
                                 content=body,
                                 c_name=c_name,
                                 c_id=int(request.POST.get('column_id'))
                                 )
            newArticle.save()
            c['statusCode'] = 200
            return JsonResponse(c)
        except Exception as e:
            return render(request, '500.html', {'error': e})
            # c['statusCode'] = 404
            # return JsonResponse(c)

    if request.method == "GET":
        if request.GET.get('column'):
            target = request.user.article_column.filter(c_name=request.GET.get('column')).all()
            if target.exists():
                return render(request, 'article_post.html', {'columns': target})
        columns = request.user.article_column.all()
        c = {
            'columns': columns,
        }
        return render(request, 'article_post.html', c)


@login_required(login_url='/account/login/')
@csrf_exempt
def user_articles(request):
    if request.method == "GET":
        if request.GET.get('author_id'):
            name = User.objects.get(pk=request.GET.get('author_id'))
            articles = Article.objects.filter(u_id=request.GET.get('author_id'))
            return render(request, 'user_articles.html',
                          {'articles': articles, 'author_id': request.GET.get('author_id'), 'author_name': name})
        else:
            name = User.objects.get(pk=request.user.id)
            articles = Article.objects.filter(u_id=request.user.id)
            return render(request, 'user_articles.html',
                          {'articles': articles, 'author_id': request.user.id, 'author_name': name})

    if request.method == "POST":
        if request.POST.get("detail") and request.POST.get('detail') != 'NaN':
            articles = Article.objects.filter(u_id=request.POST.get('u_id')).filter(
                Q(title__contains=request.POST.get('detail')) | Q(c_name__contains=request.POST.get('detail')))
            return JsonResponse({'status': 'true', 'data': list(articles.values())},
                                json_dumps_params={"ensure_ascii": False})
        else:
            articles = Article.objects.filter(u_id=request.POST.get('u_id'))
            return JsonResponse({'status': 'true', 'data': list(articles.values())},
                                json_dumps_params={"ensure_ascii": False})


def get_img(user):
    with open(f'./{user.profile}', 'rb') as f:
        return base64.b64encode(f.read()).decode()


@login_required(login_url='/account/login/')
@csrf_exempt
def show_article(request):
    if request.method == 'GET':
        a_id = request.GET.get('a_id')
        article = Article.objects.get(pk=a_id)
        c = {
            'article': article,
            # 获取当前文章作者的头像
            'imgAuthorData': get_img(article.u),
            # 获取当前用户的头像
            'imgUserData': get_img(User.objects.get(pk=request.user.id))

        }
        return render(request, 'show_article.html', c)
    else:
        return redirect('/account/login/')


@login_required(login_url='/account/login/')
@csrf_exempt
def article_square(request):
    if request.method == 'GET':
        imgUserData = get_img(User.objects.get(pk=request.user.id))
        return render(request, 'articles.html', locals())
    if request.method == 'POST':
        pageSize = 10
        if request.GET.get('query'):
            articles = Article.objects.filter(title__contains=request.GET.get('query'))
        else:
            articles = Article.objects.all()
        # 设置分页，设置每页最多几个，每页最多三个
        paginator = Paginator(articles, 3)
        # 获取当前页
        page = request.GET.get('page')
        try:
            current_page = paginator.page(page)
            articles = current_page.object_list
            page = int(page)
        except PageNotAnInteger:
            current_page = paginator.page(1)
            articles = current_page.object_list
            page = 1
        except EmptyPage:
            current_page = paginator.page(paginator.num_pages)
            articles = current_page.object_list
            page = paginator.num_pages
        data = articles.values()
        for item in data:
            item['UserName'] = User.objects.get(pk=item['u_id']).username
            item['LikeCount'] = Article.objects.get(pk=item['id']).like.count()
            item['CommentCount'] = Article.objects.get(pk=item['id']).comment_set.count()
        return JsonResponse({'data': list(data), 'msg': 'success', 'pageSize': pageSize, 'page': page})


@csrf_exempt
@require_POST
@login_required(login_url='/account/login/')
def article_action(request):
    a_id = request.POST.get("a_id")
    action = request.POST.get("action")
    if a_id and action:
        try:
            article = Article.objects.get(pk=a_id)
            if action == "like":
                article.like.add(request.user)
                return JsonResponse({'msg': '给文章赞一个~', 'status': 'success'})
            if action == 'unlike':
                article.like.remove(request.user)
                return JsonResponse({'msg': '取消成功', 'status': 'success'})
            if action == 'eye':
                article.eye.add(request.user)
                return JsonResponse({'msg': '正在看~', 'status': 'success'})
            if action == 'uneye':
                article.eye.remove(request.user)
                return JsonResponse({'msg': '取消成功', 'status': 'success'})
            if action == 'collect':
                article.collect.add(request.user)
                return JsonResponse({'msg': '文章已收藏~', 'status': 'success'})
            if action == 'uncollect':
                article.collect.remove(request.user)
                return JsonResponse({'msg': '取消成功', 'status': 'success'})
        except:
            return JsonResponse({'msg': '未知错误', 'status': 'error'})
